<?php

namespace App\Http\Controllers\App;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\ShopUserBalanceLog;
use App\Models\ShopUserCenter;
use App\Models\ExChange;
use App\Models\LinesLog;
use App\Models\Lines;
use App\Models\Queue;
use App\Models\User;
use App\Models\Card;

/**
 * 积分兑换管理控制器
 */
// class ExChangeController extends Controller
class ExChangeController extends BaseController
{
    /**
     * 兑换列表(GET) api/ex/lists
     * 
     * @return json
     */
    public function lists(Request $request)
    {
// 测试数据
// $shopInfo = $request->session()->put('shopInfo',['id'=>1]);
        // 商户SESSION数据
        $shopInfo = $request->session()->get('shopInfo');

        // 商户状态判断
        $shop_id = $shopInfo['id'];     // 店铺id
        if(!$shop_id){
            return self::error('未登录');
        }

        // 实例化模型
        $ex     = new ExChange;
        $user   = new User;

        // $where['user_mobile'] = 18595602136;
        $where['e.shop_id'] = $shop_id;

        // 检索条件
        $request->input('user_mobile')  == null || $where['user_mobile']    = $request->input('user_mobile');   // 手机号
        $request->input('status')       == null || $where['e.status']       = $request->input('status');        // 状态
        
        // 查询列表
        $query = DB::table($ex['table'].' as e')
                ->leftJoin($user['table'].' as u' , 'e.userid' , '=' ,'u.id')
                ->where($where);

        $request->input('s_time')   == null || $query->whereDate('e.created_at','>=',$request->input('s_time')); // 开始时间
        $request->input('e_time')   == null || $query->whereDate('e.created_at','<=',$request->input('e_time')); // 开始时间

        $data = $query
                ->select('e.id' , 'e.order_id' , 'e.total' , 'e.actual' , 'e.poundage' , 'e.percent' , 'e.status' , 'e.created_at' , 'user_mobile' , 'u.id as user_id')
                ->paginate(10);

        // 队列名称
        $q_name = Queue::where('shop_id',$shop_id)->value('name');
                
        return self::json(['ec_info'=>$data,'q_name'=>$q_name] , '查询成功');
    }

    /**
     * 服务费列表 api/ex/serv
     */
    public function serviceCharge(Request $request)
    {
// 测试数据
// $shopInfo = $request->session()->put('shopInfo',['id'=>1]);
        // 商户SESSION数据
        $shopInfo = $request->session()->get('shopInfo');

        // 商户状态判断
        $shop_id = $shopInfo['id'];     // 店铺id
        if(!$shop_id){
            return self::error('未登录');
        }

        // 实例化模型
        $ex     = new ExChange;
        $user   = new User;

        // 查询列表
        $return = DB::table($ex['table'].' as e')
                ->leftJoin($user['table'].' as u' , 'e.userid' , '=' , 'u.id')
                ->where('e.status',1)
                ->where('e.shop_id',$shop_id)
                ->select('order_id' , 'total' , 'e.created_at' , 'poundage' , 'percent' , 'user_mobile')
                ->paginate(10);

        return self::json($return , '查询成功');
    }

    /**
     * 兑换申请详情 api/ex/info
     * 
     * @return json
     */
    public function info(Request $request)
    {
        // 兑换申请id
        $id = $request->input('id');                      
        if(!$id){
            return self::error('参数不完整');
        }

        // 实例化模型
        $ex     = new ExChange;
        $user   = new User;
        $card   = new Card;

        // 兑换信息
        $data = DB::table($ex['table'].' as e')
                ->leftJoin($user['table'].' as u' , 'e.userid' , '=' , 'u.id')
                ->leftJoin($card['table'].' as c' , 'e.userid' , '=' , 'c.user_id')
                ->select('e.id' , 'e.order_id' , 'e.total' , 'e.actual' , 'e.poundage' , 'e.percent' , 'real_name' , 'user_mobile' , 'id_card' , 'card_num')
                ->first();

        return self::json($data , '查询成功');
        
    }

    /**
     * 兑换审核(POST) api/ex/check
     * 
     * @return json
     */
    public function check(Request $request)
    {
// 测试数据
// $shopInfo = $request->session()->put('shopInfo',['id'=>1]);
        // 商户SESSION数据
        $shopInfo = $request->session()->get('shopInfo');

        // 商户状态判断
        $shop_id = $shopInfo['id'];                     // 店铺id
        if(!$shop_id){
            return self::error('未登录');
        }

        // 兑换信息id
        $id = $request->input('id');                    
        if(!$id){
            return self::error('参数不完整');
        }

        // 申请信息
        $ex_info = ExChange::where('id',$id)->first();
        if(!$ex_info){
            return self::error('申请不存在');
        }

        if($ex_info['shop_id'] != $shop_id){
            return self::error('非本店铺订单');
        }

        if($ex_info['status'] != 0){
            return self::error('申请信息有误');
        }
        
        // 用户在本商户资金中心
        $balance_info = ShopUserCenter::where('user_id',$ex_info['userid'])->where('shop_id',$shop_id)->where('status',1)->first();
        if(!$balance_info){
            return self::error('与用户无绑定信息');
        } 

        // 开启事务
        DB::beginTransaction();
        try{

            // 审核通过
            $re = ExChange::where('id',$id)->update(['status'=>1]);
            if(!$re){
                return self::error('兑换失败');
            }

            // 获取订单所在队列
            $queue = Lines::where('order_id',$ex_info['order_id'])->value('queue');

            // 更改订单状态
            $re_lines = Lines::where('order_id',$ex_info['order_id'])
                        ->update([
                            'finish_time'   => time(),
                            'status'        => 3,
                        ]); 
            
            // 记录日志
            $lines_log = new LinesLog;
            $lines_log->queue       = $queue;
            $lines_log->order_id    = $ex_info['order_id'];
            $lines_log->log         = "兑换成功";
            $lines_log->save();

            // 充入用户余额
            $in_balance = ShopUserCenter::where('user_id' , $ex_info['userid'])
                        ->where('shop_id' , $shop_id)
                        ->update([
                                'balance' => $balance_info['balance']+$ex_info['actual']
                        ]);

            // 用户手机号
            $user_mobile = User::where('id',$ex_info['userid'])->value('user_mobile');

            // 记录用户流水
            $ShopUserBalanceLog = new ShopUserBalanceLog;
            $ShopUserBalanceLog->user_id    = $ex_info['userid'];
            $ShopUserBalanceLog->shop_id    = $shop_id;
            $ShopUserBalanceLog->order_sn   = $ex_info['order_id'];
            $ShopUserBalanceLog->money      = $ex_info['actual'];
            $ShopUserBalanceLog->type       = 3;                    // 3积分兑换
            $ShopUserBalanceLog->action_type= 2;                    // 用户收入
            $ShopUserBalanceLog->status     = 2;                    // 审核通过
            $ShopUserBalanceLog->user_mobile=$user_mobile;          // 用户手机号
            $ShopUserBalanceLog->note       = "积分兑换";           // 日志信息
            $ShopUserBalanceLog->save();

            // 提交事务
            DB::commit();

            return self::success('审核通过');

        }catch (\Exception $e) {

            // 回滚事务
            DB::rollback();

            return self::json($e , '审核出错' , 400);
        }

    }

    /**
     * 拒绝兑换(POST) api/ex/refuse
     */
    public function refuse(Request $request)
    {
// 测试数据
// $shopInfo = $request->session()->put('shopInfo',['id'=>1]);
        // 商户SESSION数据
        $shopInfo = $request->session()->get('shopInfo');

        // 商户状态判断
        $shop_id = $shopInfo['id'];                     // 店铺id
        if(!$shop_id){
            return self::error('未登录');
        }

        // 兑换信息id
        $id = $request->input('id');        
        if(!$id){
            return self::error('参数不完整');
        }

        // 申请信息
        $ex_info = ExChange::where('id',$id)->first();
        if(!$ex_info){
            return self::error('申请不存在');
        }

        if($ex_info['shop_id'] != $shop_id){
            return self::error('非本店铺订单');
        }

        if($ex_info['status'] != 0){
            return self::error('申请信息有误');
        }

        // 开启事务
        DB::beginTransaction();
        try{

            // 拒绝
            $re = ExChange::where('id',$id)->update(['status'=>2,'note'=>$request->input('note')]);
            if(!$re){
                return self::error('拒绝失败');
            }

            // 获取订单所在队列
            $queue = Lines::where('order_id',$ex_info['order_id'])->value('queue');

            // 更改订单状态
            $re_lines = Lines::where('order_id',$ex_info['order_id'])
                        ->update([
                            'status'        => 4,
                            'note'          => $request->input('note')
                        ]); 
            
            // 记录日志
            $lines_log = new LinesLog;
            $lines_log->queue       = $queue;
            $lines_log->order_id    = $ex_info['order_id'];
            $lines_log->log         = "商户拒绝兑换申请";
            $lines_log->save();


            // 提交事务
            DB::commit();

            return self::success('已拒绝');

        }catch (\Exception $e) {

            // 回滚事务
            DB::rollback();

            return self::json($e , '审核出错' , 400);
        }
    }

    

    

}
